


Graph.prototype.addEdge = function(start, end, style) {
    if (this.getEdge(start, end) || start == end)
        return false;
    var s = this.addNode(start);
    var t = this.addNode(end);
    var edge = this.edgeFactory.build(s, t);
    edge.weight = style && style.label ? style.label : 0;
    if (style && !style.label) {
        style.label = "";
    }
    jQuery.extend(edge.style, style);
    // NOTE: Even directed edges are added to both nodes.
    s.edges.push(edge);
    this.edges.push(edge);
    t.edges.push(edge);

    return true;
};

Graph.prototype.getEdge = function(start, end) {
    for (var i = 0; i < this.edges.length; i++) {
        var edge = this.edges[i];
        if (edge.source.id == start && edge.target.id == end) {
            return edge;
        }
    }
};

Graph.prototype.removeNode = function(id) {
    this.nodes[id].shape.remove();
    delete this.nodes[id];
    for (var i = 0; i < this.edges.length; i++) {
        var edge = this.edges[i];
        var isSource = (edge.source.id == id);
        var isTarget = (edge.target.id == id);
        if (isSource || isTarget) {
            edge.connection.fg.remove();
            var label = edge.connection.label;
            label && label.remove();
            this.edges.splice(i, 1);
            i--;
            var idOfNeighbour = edge.target.id;
            if (isTarget) {
                idOfNeighbour = edge.source.id;
            }
            this.removeEdgeFromVerticeList(edge, idOfNeighbour);
        }
    }
};

Graph.prototype.removeEdge = function(start, end) {
    var edge = this.getEdge(start, end);
    edge.connection.fg.remove();
    var label = edge.connection.label;
    label && label.remove();
    this.removeEdgeFromMainList(edge);
    this.removeEdgeFromVerticeList(edge, start);
    this.removeEdgeFromVerticeList(edge, end);
};

Graph.prototype.removeEdgeFromMainList = function(edgeToRemove) {
    for (var i = 0; i < this.edges.length; i++) {
        var edge = this.edges[i];
        if (edge === edgeToRemove) {
            this.edges.splice(i, 1);
            break;
        }
    }
};

Graph.prototype.removeEdgeFromVerticeList = function(edgeToRemove, id) {
    for (var i = 0; i < this.nodes[id].edges.length; i++) {
        var edge = this.nodes[id].edges[i];
        if (edge === edgeToRemove) {
            this.nodes[id].edges.splice(i, 1);
            break;
        }
    }
};
